package com.bawei.wyg.greendaomodel;

import org.greenrobot.greendao.query.WhereCondition;

import java.lang.reflect.ParameterizedType;
import java.util.List;

public class DaoCRUDImpl<T> implements DaoCRUD<T> {

    private Class clazz;
    public DaoCRUDImpl(){
        ParameterizedType parameterizedType= (ParameterizedType) getClass().getGenericSuperclass();
        clazz= (Class) parameterizedType.getActualTypeArguments()[0];
     }

    @Override
    public boolean insert(T t) {
        return DaoSessionUtils.getDaoSessionUtils().getDaoSession().insert(t)>0;
    }

    @Override
    public boolean inserts(List<T> datas) {
        boolean flag=true;
        for (T t: datas
             ) {
            flag=insert(t);
            if(!flag)
                break;
        }
        return flag;
    }

    @Override
    public boolean delete(T t) {
        DaoSessionUtils.getDaoSessionUtils().getDaoSession().delete(t);
        return true;
    }

    @Override
    public boolean deletes(List<T> datas) {
        for (T t:datas
             ) {
            delete(t);
        }
        return true;
    }

    @Override
    public boolean update(T t) {
        return DaoSessionUtils.getDaoSessionUtils().getDaoSession().insertOrReplace(t)>0;
    }

    @Override
    public boolean updates(List<T> datas) {
        boolean flag=true;
        for (T t: datas
        ) {
            flag=update(t);
            if(!flag)
                break;
        }
        return flag;
    }

    @Override
    public T select(WhereCondition whereCondition) {
        T t;
        t= (T) DaoSessionUtils.getDaoSessionUtils().getDaoSession().queryBuilder(clazz).where(whereCondition).unique();

        return t;
    }

    @Override
    public List<T> selectAll() {
        return DaoSessionUtils.getDaoSessionUtils().getDaoSession().queryBuilder(clazz).list();
    }
}
